package com.wonyesoft.wuliu.acticity;

import httptools.HttpJsonTool;

import java.io.File;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javabeen.UserInfoBeen;

import org.json.JSONException;
import org.json.JSONObject;

import tools.ImageFactory;

import View.DatePickerFragment;
import View.DatePickerFragment.onChoseData;
import View.InPutDialog;
import View.InPutDialog.getChoseTYPE;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;
import com.wonyesoft.wuliu.AppContent;
import com.wonyesoft.wuliu.R;
import com.wonyesoft.wuliu.acticity.base.BaseActivity;
import com.wonyesoft.wuliu.acticity.utils.FileUtils;
import com.wonyesoft.wuliu.acticity.utils.ToastUtils;
import com.wonyesoft.wuliu.api.GagApi;

import com.wonyesoft.wuliu.model.User;
import com.wonyesoft.wuliu.vo.JsonRequest;
import com.wonyesoft.wuliu.vo.JsonResponse;
import com.wonyesoft.wuliu.vo.State;

public class UserNewInfoActivity extends BaseActivity implements
		OnClickListener {

	private AppContent app;

	private static final String IMAGE_PATH = Environment
			.getExternalStorageDirectory().toString()
			+ File.separator
			+ "tczh"
			+ File.separator + "Images" + File.separator;

	/**
	 * 图片路径
	 */
	private String mTakePicturePath;

	private EditText cargoownername;

	private EditText job;

	private EditText email;

	private EditText wechartid;

	private EditText qq;

	private EditText idcardno;

	private TextView birthday;

	private ImageView head_left;

	private RequestParams params;

	private Button user_newinfo_baocun;

	private String[] sex = new String[] { "男", "女" };

	private int selectedFruitIndex = 0;

	private HttpUtils http = new HttpUtils();

	private PreferencesCookieStore preferencesCookieStore;

	private Gson gson = new Gson();

	private Map<String, Object> dataMap = new HashMap<String, Object>();

	private Map<String, String> imageMap = new HashMap<String, String>();

	private  UserInfoBeen userInfoBeen;
	
	private ImageView headcargoImageView;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_newinfo);
		blindIds();
		user_newinfo_baocun.setOnClickListener(this);
		head_left = (ImageView) findViewById(R.id.head_left);
		head_left.setVisibility(View.VISIBLE);
		head_left.setOnClickListener(this);
		initViews();
	}

	private void save() {
		showLoadingDialog("数据保存中...");
		if (app.userId == null) {
			openActivity(UserLoginActivity.class);
			dismissLoadingDialog();
			this.finish();
			return;
		}
		dataMap.put("cargoownerid", app.userId);
		getInputData();
		
		Type type = new TypeToken<List<UserInfoBeen>>() {
		}.getType();
		HttpJsonTool httpJsonTool = new HttpJsonTool(this);
		httpJsonTool.SetOnLister(new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				if (msg.what == 1) {
//					Toast.makeText(UserNewInfoActivity.this, (String) msg.obj,
//							Toast.LENGTH_LONG).show();
					List<UserInfoBeen> data=(List<UserInfoBeen>) msg.obj;
					if (data.size()>0) {
						app.userinfobeen=data.get(0);
						Toast.makeText(UserNewInfoActivity.this, "信息完善成功",
								Toast.LENGTH_LONG).show();
					}
					UserNewInfoActivity.this.setResult(111);
					saveimage();
				} else {
					Toast.makeText(UserNewInfoActivity.this, (String) msg.obj,
							Toast.LENGTH_LONG).show();
				}
			}
		});
		httpJsonTool.StartWork(dataMap, GagApi.UPDATA_CARGO_OWNER_INFO, type,
				null);
	}

	protected void initViews() {

		if (app.userinfobeen != null) {
			userInfoBeen = app.userinfobeen;
		} else {
			openActivity(UserLoginActivity.class);
			this.finish();
		}
		if (userInfoBeen.getsBirthday() != null) {
			TextView user_info_Birthday = (TextView) findViewById(R.id.cargoowner_info_cargoownerbirthday);
		//	Date a=new Date(userInfoBeen.getBirthday());
		//	SimpleDateFormat viewShowFormat = new SimpleDateFormat("yyyy年MM月dd日");
		//	viewShowFormat
			user_info_Birthday.setText(userInfoBeen.getsBirthday());
		}
		if (userInfoBeen.getCargoownername()!=null) {
			TextView user_info_Birthday = (TextView) findViewById(R.id.cargoowner_info_cargoownername);
			user_info_Birthday.setText(userInfoBeen.getCargoownername());
		}
		
		if (userInfoBeen.getEmail()!=null) {
			TextView cargoowner_info_email=(TextView) findViewById(R.id.cargoowner_info_caemail);
			cargoowner_info_email.setText(userInfoBeen.getEmail());
		}
		if (userInfoBeen.getJob()!=null) {
			TextView cargoowner_info_Job=(TextView) findViewById(R.id.cargoowner_info_Job);
			cargoowner_info_Job.setText(userInfoBeen.getJob());
		}
		if (userInfoBeen.getWechartid()!=null) {
			TextView cargoowner_info_Wechartid=(TextView) findViewById(R.id.cargoowner_info_cargoownerwechartid);
			cargoowner_info_Wechartid.setText(userInfoBeen.getWechartid());
		}
		if (userInfoBeen.getQq()!=null) {
			TextView cargoowner_info_Qq=(TextView) findViewById(R.id.cargoowner_info_cargoownerqq);
			cargoowner_info_Qq.setText(userInfoBeen.getQq());
		}
		if (userInfoBeen.getHeadportrait()!=null) {
			headcargoImageView=(ImageView) findViewById(R.id.user_head);
			BitmapUtils bitmapUtils=new BitmapUtils(this);
			bitmapUtils.display(headcargoImageView, GagApi.IMAGE_PAHT_HOST+userInfoBeen.getHeadportrait());
		}
	}
	
	
	
	private void saveimage() {
		// TODO Auto-generated method stub
		if (imageMap.isEmpty()) {
			dismissLoadingDialog();
			UserNewInfoActivity.this.finish();
			return;
		}
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("cargoownerid", app.userId);
		Type type = new TypeToken<List<UserInfoBeen>>() {
		}.getType();
		HttpJsonTool httpJsonTool = new HttpJsonTool(this);
		httpJsonTool.SetOnLister(new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				dismissLoadingDialog();
				super.handleMessage(msg);
				if (msg.what == 1) {
//					Toast.makeText(UserNewInfoActivity.this, (String) msg.obj,
//							Toast.LENGTH_LONG).show();
					List<UserInfoBeen> data=(List<UserInfoBeen>) msg.obj;
					if (data.size()>0) {
						app.userinfobeen=data.get(0);
					}
					UserNewInfoActivity.this.finish();
				}
			}
		});
		httpJsonTool.StartWork(hashMap, GagApi.UPDATA_CARGO_OWNER_PHOTO, type,
				imageMap);

	}

	private void getInputData() {
		if (cargoownername.getText().toString().length() > 0) {
			dataMap.put("cargoownername", cargoownername.getText().toString());
		}
		if (job.getText().toString().length() > 0) {
			dataMap.put("job", job.getText().toString());
		}
		if (email.getText().toString().length() > 0) {
			dataMap.put("email", email.getText().toString());
		}
		if (wechartid.getText().toString().length() > 0) {
			dataMap.put("wechartid", wechartid.getText().toString());
		}
		if (qq.getText().toString().length() > 0) {
			dataMap.put("qq", qq.getText().toString());
		}
		if (idcardno.getText().toString().length() > 0) {
			dataMap.put("idcardno", idcardno.getText().toString());
		}

	}

	private void blindIds() {
		app = (AppContent) getApplication();
		head_left = (ImageView) findViewById(R.id.head_left);
		TextView head_title = (TextView) findViewById(R.id.head_title);
		TextView head_right = (TextView) findViewById(R.id.head_right);
		head_right = (TextView) findViewById(R.id.head_right);
		head_right.setVisibility(View.VISIBLE);
		head_right.setOnClickListener(this);
		head_right.setText("保存");
		head_title = (TextView) findViewById(R.id.head_title);
		head_title.setText("修改个人资料");

		cargoownername = (EditText) findViewById(R.id.cargoowner_info_cargoownername);
		job = (EditText) findViewById(R.id.cargoowner_info_cargoownerjob);
		email = (EditText) findViewById(R.id.cargoowner_info_caemail);
		wechartid = (EditText) findViewById(R.id.cargoowner_info_cargoownerwechartid);
		qq = (EditText) findViewById(R.id.cargoowner_info_cargoownerqq);
		idcardno = (EditText) findViewById(R.id.cargoowner_info_cargoowneridcardno);
		birthday = (TextView) findViewById(R.id.cargoowner_info_cargoownerbirthday);

		birthday.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				showAlertDialog(birthday);
			}
		});
		user_newinfo_baocun = (Button) findViewById(R.id.user_newinfo_baocun);
		head_left.setOnClickListener(this);
		head_title.setOnClickListener(this);
		head_right.setOnClickListener(this);

		ImageView imageView = (ImageView) findViewById(R.id.user_head);
		imageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				showPhotoAlertDialog();
			}
		});
	}

	private void showPhotoAlertDialog() {
		InPutDialog inPutDialogs = new InPutDialog(this, "", "",null,null);
		inPutDialogs.setGetChoseTYPE(new getChoseTYPE() {

			@Override
			public void getImageTYPE(int type) {
				// TODO Auto-generated method stub
				if (type == 1) {
					openImage(type);
				}
				if (type == 2) {
					openImage(type);
				}
			}
		});
		inPutDialogs.getPhotoDialog(null,null);

	}

	private void openImage(int type) {
		if (type == 1) {
			FileUtils.createDirFile(IMAGE_PATH);
			Intent intent;
			intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			String path = IMAGE_PATH + UUID.randomUUID().toString() + ".jpg";
			mTakePicturePath = path;
			File file = FileUtils.createNewFile(path);
			if (file != null) {
				intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
			}
			startActivityForResult(intent, 1);

		}
		if (type == 2) {
			Intent intent2 = new Intent(Intent.ACTION_PICK, null);
			intent2.setDataAndType(
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
			startActivityForResult(intent2, 2);

		}
	}

	private void showAlertDialog(final TextView inputDate) {
		DatePickerFragment datePickerFragment = new DatePickerFragment(this,
				"2012年07月02日 00:00", false,"请选择您的生日","取消已选择");
		datePickerFragment.setOnChoseData(new onChoseData() {

			@Override
			public void getChoseData(Boolean isChose, String dataString) {
				// TODO Auto-generated method stub
				if (isChose) {
					dataMap.put("birthday", dataString);
				} else {
					dataMap.remove("birthday");
					birthday.setText("");
					birthday.setHint("点击选择您的生日");
				}

			}
		});
		datePickerFragment.dateTimePicKDialog(inputDate);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.user_newinfo_baocun:
			save();
			break;
		// case R.id.user_newinfo_sex:
		// getSex();
		// break;
		case R.id.head_left:
			finish();
			break;
		case R.id.head_right:
			save();
			break;

		default:
			break;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 0) {
			return;
		}
		if (requestCode == 1) {
			imageMap.put("headPortraitFlie", mTakePicturePath);
			ImageView imageView = (ImageView) findViewById(R.id.user_head);
			BitmapUtils bitmapUtils = new BitmapUtils(this);
			bitmapUtils.display(imageView, mTakePicturePath);
		}
		if (requestCode == 2) {
			if (data == null) {
				return;
			}
			Uri uri = data.getData();
			String[] proj = { MediaStore.Images.Media.DATA };
			Cursor cursor = managedQuery(uri, proj, null, null, null);
			if (cursor != null) {
				int column_index = cursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				if (cursor.getCount() > 0 && cursor.moveToFirst()) {
					String path = cursor.getString(column_index);
					ImageView imageView = (ImageView) findViewById(R.id.user_head);
					BitmapUtils bitmapUtils = new BitmapUtils(this);
					bitmapUtils.display(imageView, path);
					// 压缩图片
					ImageFactory.compressImage(path, 10);

					imageMap.put("headPortraitFlie", path);
				}
			}
		}

	}

}
